package com.lyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lyj.exception.BaseException;
import com.lyj.mapper.DeviceMapper;
import com.lyj.mapper.DeviceRoomMappingMapper;
import com.lyj.mapper.RoomMapper;
import com.lyj.pojo.Device;
import com.lyj.pojo.DeviceRoomMapping;
import com.lyj.pojo.Room;
import com.lyj.pojo.dto.DeviceAddDTO;
import com.lyj.pojo.dto.DeviceEditDTO;
import com.lyj.pojo.vo.AvailableDeviceVO;
import com.lyj.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private DeviceRoomMappingMapper mappingMapper;

    @Autowired
    private RoomMapper roomMapper;

    @Override
    public List<Device> getDeviceList(Integer familyId, Integer roomId, Integer isOnline) {
        if (familyId == null) {
            throw new BaseException("家庭ID不能为空");
        }
        return deviceMapper.selectByFamilyAndRoom(familyId, roomId, isOnline);
    }

    @Transactional
    @Override
    public void editDevice(DeviceEditDTO deviceEditDTO) {
        // 验证设备是否存在
        Device device = deviceMapper.selectById(deviceEditDTO.getDeviceId());
        if (device == null) {
            throw new BaseException("设备不存在");
        }

        // 验证房间是否存在
        Room room = roomMapper.selectById(deviceEditDTO.getRoomId());
        if (room == null) {
            throw new BaseException("房间不存在");
        }

        // 验证设备和房间是否属于同一家庭
        if (!device.getFamilyId().equals(room.getFamilyId())) {
            throw new BaseException("设备和房间不属于同一家庭");
        }

        // 更新设备名称
        device.setDeviceName(deviceEditDTO.getDeviceName());
        deviceMapper.updateById(device);

        // 更新设备与房间的映射关系
        DeviceRoomMapping mapping = mappingMapper.selectByDeviceId(device.getDeviceId());
        if (mapping == null) {
            mapping = new DeviceRoomMapping();
            mapping.setDeviceId(device.getDeviceId());
            mapping.setRoomId(deviceEditDTO.getRoomId());
            mappingMapper.insert(mapping);
        } else {
            mapping.setRoomId(deviceEditDTO.getRoomId());
            mappingMapper.updateById(mapping);
        }
    }

    @Transactional
    @Override
    public void deleteDevice(Integer deviceId, Integer familyId) {
        // 验证设备是否存在
        Device device = deviceMapper.selectById(deviceId);
        if (device == null) {
            throw new BaseException("设备不存在");
        }

        // 验证权限
        if (!device.getFamilyId().equals(familyId)) {
            throw new BaseException("无权限删除此设备");
        }

        // 删除映射关系
        mappingMapper.deleteByDeviceId(deviceId);

        Device device1 = new Device(device.getDeviceId(),device.getFamilyId(),device.getDeviceName(),0,0);
        // 删除设备
        deviceMapper.updateById(device1);
    }

    @Override
    public List<AvailableDeviceVO> getAvailableDevices(Integer familyId) {
        if (familyId == null) {
            throw new BaseException("家庭ID不能为空");
        }
        return deviceMapper.selectByFamilyId(familyId);
    }

    @Transactional
    @Override
    public Device activateOfflineDevice(DeviceAddDTO deviceAddDTO) {
        // 1. 查找家庭中同名的离线设备
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getFamilyId, deviceAddDTO.getFamilyId())
                .eq(Device::getDeviceName, deviceAddDTO.getDeviceName())
                .eq(Device::getIsOnline, 0); // 只查找离线设备

        Device offlineDevice = deviceMapper.selectOne(queryWrapper);
        if (offlineDevice == null) {
            throw new BaseException("未找到该名称的离线设备");
        }

        // 2. 将设备标记为在线
        offlineDevice.setIsOnline(1);
        deviceMapper.updateById(offlineDevice);

        return offlineDevice;
    }

    @Override
    public Integer togglePowerStatus(Integer deviceId, Integer familyId) {
        // 1. 验证设备是否存在
        Device device = deviceMapper.selectById(deviceId);
        if (device == null) {
            throw new BaseException("设备不存在");
        }

        // 2. 验证权限（属于同一家庭）
        if (!device.getFamilyId().equals(familyId)) {
            throw new BaseException("无权限控制此设备");
        }

        // 3. 切换开关状态（0→1 或 1→0）
        device.setPowerStatus(device.getPowerStatus() == 1 ? 0 : 1);
        deviceMapper.updateById(device);

        // 4. 返回新状态
        return device.getPowerStatus();
    }
}